<?php

namespace App\Models;

use App\Models\SubTaskLog;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class SubTask extends Model
{
    use HasFactory, SoftDeletes;

    const STATUS_INITIALIZED = 1;
    const STATUS_WAIT_REVIEW1 = 2;
    const STATUS_REJECTION1 = 3;
    const STATUS_WAIT_REVIEW2 = 4;
    const STATUS_REJECTION2 = 5;
    const STATUS_COMPLETED = 6;

    const REVIEW_RESULT_YES = 1;
    const REVIEW_RESULT_NO = 2;

    protected $fillable = ['task_id', 'district_id'];

    protected $hidden = ['deleted_at'];

    protected $casts = [
        'data' => 'json',
    ];

    public function task()
    {
        return $this->belongsTo(Task::class);
    }

    public function district()
    {
        return $this->belongsTo(District::class)->select(['id', 'name']);
    }

    public function logs()
    {
        return $this->hasMany(SubTaskLog::class);
    }

    public function reportLog(): Attribute
    {
        return Attribute::make(
            get: fn() => $this->logs()->with('operator')->whereOperationType(SubTaskLog::OPERATION_REPORT)->latest()->first(),
        );
    }

    public function review1Log(): Attribute
    {
        return Attribute::make(
            get: fn() => $this->logs()->with('operator')->whereOperationType(SubTaskLog::OPERATION_REVIEW1)->latest()->first(),
        );
    }
}
